jQuery(document).ready(function(){

	// Dropdown menu
	$("ul.topnav li a").mouseover(function() { //When trigger is clicked...
		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click
		$(this).parent().hover(function() {
		}, function(){
			$(this).parent().find("ul.subnav").hide(); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
		}).hover(function() { 
			$(this).addClass("subhover"); //On hover over, add class "subhover"
		}, function(){	//On Hover Out
			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});


	if(jQuery("#badMessage")){
		jQuery("#badMessage").delay(10000).fadeOut(400);
	}

	if(jQuery("#goodMessage")){
		jQuery("#goodMessage").delay(10000).fadeOut(400);
	}

	jQuery(".number-mipt").focus(function(){
		this.select();
	});

	jQuery(".number-mipt").keypress(function(evt){
		var charCode = (evt.which) ? evt.which : evt.keyCode
		if ((charCode > 47 && charCode < 58) || charCode == 8)
			return true;
		return false;
	});

	/*========= SLUG ==========*/
	jQuery(".title-slug").blur(function(){
		if(jQuery(this).length > 0){
			var titleSlug = jQuery(this).val();
			var slug = generateSlug(titleSlug);  
			jQuery(".slug-string").val(slug);
		}
	});

	/*======== OPTION TYPES ====*/
	if(jQuery('#add-more-link')){
		jQuery('#add-more-link').click(function(){
			var html_str = "<tr><td width='70%' class='width_full'><input type='text' value='' class='required' id='OptionValues" + countOptionValue + "Name' name='data[OptionValues][" + 		countOptionValue + "][name]'> </td>\
										  <td class='action-cm'><a href='#' onclick='removed(this);' class='act-lk del-link required'>Delete</a></td></tr>";
    	jQuery('#option-value').append(html_str);
			countOptionValue++;
		});
	}

	if(jQuery("#OptionTypeAddForm")){
		jQuery("#OptionTypeAddForm").validate();
	}

	if(jQuery("#OptionTypeEditForm")){
		jQuery("#OptionTypeEditForm").validate();
	}

	/*======= POST ==== */
	if(jQuery("#PostAddForm").length > 0 || jQuery("#PostEditForm").length > 0){
		/*jQuery("#submit_post").click(function() {
    	var content = tinyMCE.activeEditor.getContent(); // get the content
    	jQuery("#PostContent").val(content); // put it in the textarea
		}); */
		jQuery("#PostAddForm").validate();
		jQuery("#PostEditForm").validate();
		jQuery("#PostTags").tagsInput();
	}

	/*======= CheckBox Column ==== */
	if(jQuery("#check-all").length > 0){

		jQuery(".canclick").click(function(){
			jQuery(this).parent().find(".check-item").click(); //[0].checked = !jQuery(this).parent().find(".check-item")[0].checked; 
			if(jQuery(this).parent().find(".check-item")[0].checked == false){
				jQuery("#check-all")[0].checked = false;
			}else{
				var items = jQuery(".check-item");
				var count = 0;
				for(var i=0; i<items.length; i++){
					if(items[i].checked == false){
						return;
					}
				}				
				jQuery("#check-all")[0].checked = true;
			}
		});

		jQuery("#check-all").click(function(){
			var flag = false
			if(jQuery(this)[0].checked == true){
				flag = true;
			}
			var items = jQuery(".check-item");
			for(var i=0; i<items.length; i++){
				items[i].checked = flag;
			}
		});

		jQuery(".check-item").click(function(){
			if(jQuery(this)[0].checked == false){
				jQuery("#check-all")[0].checked = false;
			}else{
				var items = jQuery(".check-item");
				var count = 0;
				for(var i=0; i<items.length; i++){
					if(items[i].checked == false){
						return;
					}
				}				
				jQuery("#check-all")[0].checked = true;
			}
		});
	}

	/*====== Slider Style ===============*/
	jQuery("#add-more-slide").click(function(){
		var html_str = "<tr>\
										<td class='col-no'><div class='input number required'>\
											<input type='number' onkeypress='return enterOnlyNumber(event);' id='Image" + countImages + "Order' value='" + countImages + "' class='number-mipt required digits valid' \
											 name='data[Image][" + countImages + "][order]'></div></td>\
										<td class='post-img-small'></td>\
										<td class='slider-images'>\
											<div class='input file'><input type='file' id='Image" + countImages + "Photo' class='required' name='data[Image][" + countImages + "][photo]'></div>\
													<input type='hidden' id='Image" + countImages + "Dir' name='data[Image][" + countImages + "][dir]'>\
													<input type='hidden' id='Image" + countImages + "Mimetype' name='data[Image][" + countImages + "][mimetype]'>\
													<input type='hidden' id='Image" + countImages + "Filesize' name='data[Image][" + countImages + "][filesize]'>\
													<input type='hidden' id='Image" + countImages + "OwnerModel' name='data[Image][" + countImages + "][owner_model]' value='Slider'>\
										</td>\
										<td style='width: 30%;'><input type='text' id='Image" + countImages + "Url' name='data[Image][" + countImages + "][url]' style='width:90%' /></td>\
										<td style='width: 25%; text-align:center;'><a href='#' onclick='removed(this);' class='act-lk del-link required'>Delete</a></td>\
									</tr>";

		jQuery("#images-slider").append(html_str);
		countImages++;	
	});
	
	jQuery("#SliderSlide").click(function(){
		if(jQuery(this)[0].checked == true){
			jQuery("#add-more-slide").show();			
		}else{
			jQuery("#add-more-slide").hide();
			//jQuery('#images-slider tr:gt(1)').remove()
			//countImages = 1;
		}
	});
	
	if(jQuery("#SliderAddForm").length > 0){
		jQuery("#SliderAddForm").validate();
	}

/*========== Product Style ================*/
	if(jQuery("#ProductAddForm").length > 0 || jQuery("#ProductEditForm").length > 0){
		jQuery("#ProductAddForm").validate();
		jQuery("#ProductEditForm").validate();
		jQuery("#ProductTags").tagsInput();
	}

/*========== Top Menu Style ===============*/
	jQuery(".has_task").click(function(){
		jQuery(".jobs_list").toggle("fast");
	});

/*========== AJax loader =====================*/
	jQuery('#ajax-loader').ajaxStart(function() {
        $(this).show();
        jQuery('#ajax-mask').show();
    }).ajaxStop(function() {
        $(this).hide();
        jQuery('#ajax-mask').hide();
  });

/*========= SimpleModal Contact ====================*/


});

function showHideMessage(){
	if(jQuery("#badMessage")){
		jQuery("#badMessage").delay(3000).fadeOut(400);
	}

	if(jQuery("#goodMessage")){
		jQuery("#goodMessage").delay(3000).fadeOut(400);
	}
}

function count_character(obj){
	if(jQuery(obj)){
		var text = jQuery(obj)[0].value;
		jQuery("#count_chars").val(text.length);
	}
}

function update_status_form(status){
	jQuery("#OptionTypeStatus").val(status);
}

function removed(obj){
	var a = $(obj).closest('tr');
	a.remove();			
}

function enterOnlyNumber(evt){
	var charCode = (evt.which) ? evt.which : event.keyCode
	if ((charCode > 47 && charCode < 58) || charCode == 8)
		return true;
	return false;
}

function notAllowComment(id, url){
	var r=confirm("Do you want to delete the selected comment?");
	if (r==true){
		jQuery.ajax({
			url: url,		
			type: "POST",
			data: {cid : id},
		}).done(function( html ) {
			jQuery("#comments-area").html(html);
		}); 
	}
}

function updateStatus(url, id, status){
	jQuery.ajax({
		url: url,		
		type: "POST",
		data: {status : status, id: id},
	}).done(function( html ) {
		jQuery("#data-content").html(html);
	});
}

function replyContact(id, url){
	jQuery.ajax({
		url: url,		
		type: "POST",
		data: {cid : id},
	}).done(function( html ) {
		jQuery("#dialog-reply").html(html);
		setUpFullTinyMCE();
		jQuery("#dialog-reply").modal({
				autoResize:true,
				escClose:false,
				modal: true,
				persist: true,
				transient:true,
				onOpen: function (dialog) {
					dialog.overlay.fadeIn('slow', function () {
						dialog.data.hide();
						dialog.container.fadeIn('slow', function () {
							//update dialog size
							jQuery("#simplemodal-container").css('height', 'auto');
							jQuery("#simplemodal-container").css('width', 'auto');
							jQuery.modal.update();
							dialog.data.slideDown('slow');	 
						});
					});
				}
		});
	});
}

function generateSlug(str){
	str = str.replace(/^\s+|\s+$/g, ''); // trim
  str = str.toLowerCase();

  var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;áàảãạăắằẳẵặâấầẩẫậđéèẻẽẹêếềểễệíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵ";
  var to   = "aaaaaeeeeeiiiiooooouuuunc------aaaaaaaaaaaaaaaaadeeeeeeeeeeeiiiiiooooooooooooooooouuuuuuuuuuuyyyyy";
  for (var i=0, l=from.length ; i<l ; i++) {
    str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
  }	

	str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
    .replace(/\s+/g, '-') // collapse whitespace and replace by -
    .replace(/-+/g, '-'); // collapse dashes
  return str;
}

